<template>
  <div class="pod">
    <el-row>
      <!-- 头部1 -->
      <el-col :span="24">
        <div>
          <el-card class="pod-head-card" shadow="never" :body-style="{padding:  '10px'}">
            <el-row>
              <!-- 命名空间 -->
              <el-col :span="6">
                <div style="display: table-row">
                  <span>命名空间 : </span>
                  <el-select v-model="namespaceValue" filterable placeholder="请选择">
                    <el-option
                    v-for="(item,index) in namespaceList"
                    :key="index"
                    :label="item.metadata.name"
                    :value="item.metadata.name">
                    </el-option>
                  </el-select>
                </div>              </el-col>
              <!-- 刷新按钮 -->
              <el-col :span="2" :offset="16">
                <div>
                  <el-button style="botder-radius:2px" icon="Refresh" plain @click="getPods()">刷新</el-button>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-col>
      <!-- 头部2 -->
      <el-col :span="24">
        <div>
          <el-card class="pod-head-card" shadow="never" :body-style="{padding:'10px'}">
            <el-row>
              <!-- 创建按钮 -->
              <el-col :span="2" >
                <div>
                  <el-button disabled style="border-radius: 2px;"
                  icon="Edit"
                  type="primary"> 创建
                  </el-button>
                </div>
              </el-col>
              <!-- 搜索框和搜索按钮 -->
              <el-col :span="6">
                <div>
                  <el-input class="pod-head-search"
                  clearable placeholder="请输入"
                  v-model="searchInput"></el-input>
                  <el-button style="border-radius:2px;"
                  icon="Search" type="primary" plain @click="getPods()"></el-button>
                </div>

              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-col>
      <!-- 数据表格 -->
      <el-col :span="24">
      <div>
        <el-card class="pod-body-card" shadow="never" :body-style="{padding: '5px'}">
          <el-table style="width: 100%;font-size:12px;margin-bottom:10px" :data="podmentList">
              <el-table-column width="20"></el-table-column>
              <el-table-column align="left" label="Pod名">
                  <template v-slot="scope">
                    <a class="pod-body-podname">{{ scope.row.metadata.name }}</a>
                  </template>
              </el-table-column>
              <el-table-column align="left" label="标签">
                <template v-slot="scope">
                  <div v-for="(val,key) in scope.row.metadata.labels" :key="key">
                    <el-popover
                    placement="right"
                    :width="200"
                    trigger="hover"
                    :content="key + ':' + val">
                      <template #reference>
                        <!-- 标签与标签之间间隔设置为5px -->
                        <el-tag style="margin-bottom:5px" type="warning">{{ ellipsis(key + ':' + val) }}</el-tag>
                      </template>
                    </el-popover>

                  </div>
                </template>
              </el-table-column>
                           <el-table-column align=center min-width="100" label="创建时间">
                  <!-- timeTrans函数用于将格林威治时间转成北京时间 -->
                  <template v-slot="scope">
                      <el-tag type="info">{{ timeTrans(scope.row.metadata.creationTimestamp) }} </el-tag>
                  </template>
              </el-table-column>
              <!-- 容器镜像 -->
              <el-table-column align=center label="镜像">
                  <!-- 与label的显示逻辑一致 -->
                  <template v-slot="scope">
                      <div v-for="(val, key) in scope.row.spec.containers" :key="key">
                          <el-popover
                              placement="right"
                              :width="200"
                              trigger="hover"
                              :content="val.image">
                              <template #reference>
                                  <el-tag style="margin-bottom: 5px">{{ ellipsis(val.image.split('/')[2]==undefined?val.image:val.image.split('/')[2]) }}</el-tag>
                              </template>
                          </el-popover>
                      </div>
                  </template>
              </el-table-column>
              <!-- 操作列，放按钮 -->
              <el-table-column align=center label="操作" width="400">
                  <template v-slot="scope">
                      <el-button size="small" style="border-radius:2px;" icon="Edit" type="primary" plain @click="getPodDetail(scope)">YAML</el-button>
                      <el-button size="small" style="border-radius:2px;" icon="Delete" type="danger" @click="handleConfirm(scope, '删除', delPod)">删除</el-button>
                  </template>
              </el-table-column>
          </el-table>
          <!-- size-change 单页大小改变后触发
          current-change 页数改变后触发
          current-page 当前页，跟后端page一致
          page-size 单页大小，跟后端limit一致 -->
          <el-pagination
            class="pod-body-pagination"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="pagesizeList"
            :page-size="pagesize"
            layout="total,sizes,prev,pager,next,jumper"
            :total="podmentTotal"></el-pagination>
        </el-card>
      </div>

      </el-col>
    </el-row>

    <!-- YAML -->
    <el-dialog title="YAML信息" v-model="yamlDialog" width="60%" top="2%">
      <codemirror
          :value="contentYaml"
          border
          :options="cmOptions"
          height="500"
          style="font-size: 14px;"
          @change="onChange">
      </codemirror>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="yamlDialog = false">取消</el-button>
          <el-button type="primary" @click="updatePod()">更新</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
  
</template>

<script>
import common from "../common/Config";
import httpClient from "../../utils/request";
import yaml2obj from 'js-yaml';
import json2yaml from "json2yaml";

export default {
  data() {
    return {
      //搜索
      searchInput: '',
      // 命名空间属性
      namespaceValue: 'default',
      namespaceList:  [],
      namespaceListUrl: common.k8sNamespaceList,
      // 列表
      apploading: false,
      podmentList: [],
      podmentTotal: 0,
      getPodData: {
          url: common.k8sPodList,
          params: {
            filter_name: '',
            namespace: '',
            page: 1,
            limit: 10
          }
      },
      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10,20,30],
      // 编辑器配置
      cmOptions: common.cmOptions,
      contentYaml: '',

      // 详 情
      yamlDialog: false,
      podmentDetail: {},
      getpodmentDetailData: {
        url: common.k8sPodDetail,
        params: {
          // podment_name: '',
          podment: '',
          namespace: ''
        }
      },
      // 更新
      updatePodData: {
        url: common.k8sPodUpdate,
        params: {
          content: '',
          namespace: ''
        }
      },
       
      //重启
      restartDialog: false,
      restartPodData: {
          url: common.k8sPodRestart,
          params: {
              podment: '',
              namespace: '',
          }
      },
      //重启
      delDialog: false,
      delPodData: {
          url: common.k8sPodDel,
          params: {
              podment: '',
              namespace: '',
          }
      },
    }
  },
  methods: {
    
    //json to yaml 
    transYaml(content) {
      return json2yaml.stringify(content)
    },
    transObj(content) {
      return yaml2obj.load(content)
    },
    // 编辑器内容发生变化时触发的方法
    onChange(val) {
      this.contentYaml = val
    },
    //分页
    handleSizeChange(size) {
      this.pagesize = size
      this.getPods()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getPods()
    },
    //格林威治时间转为北京时间
    timeTrans(timestamp) {
        let date = new Date(new Date(timestamp).getTime() + 8 * 3600 * 1000)
        date = date.toJSON();
        date = date.substring(0, 19).replace('T', ' ')
        return date 
    },
    //字符串的截取
    ellipsis(value) {
      return value.length>15?value.substring(0,15)+'...':value
    },
    // 处理抽屉的关闭，double check，增加体验
    handleClose(done){
      this.$confirm('确认关闭')
      .then(()=> {
        done();
      })
      .catch(()=>{})
    },
    getNamespacesList() {
      httpClient.get(this.namespaceListUrl)
      .then(res => {
        this.namespaceList = res.data.items
      })
      .catch(res => {
        this.$message.error({
          message: res.msg
        })
      })
    },
    // 获取podment 列表
    getPods(){
      this.apploading = true
      this.getPodData.params.filter_name = this.searchInput
      this.getPodData.params.namespace = this.namespaceValue
      this.getPodData.params.page = this.currentPage
      this.getPodData.params.limit = this.pagesize
      httpClient.get(this.getPodData.url,{params: this.getPodData.params})
      .then(res => {
        this.podmentList = res.data.items
        this.podmentTotal = res.data.total
      })
      .catch(res => {
        this.$message.error({
          message: res.msg
        })
      })
      this.apploading = false
    },
    // 获取详情, e参数标识传入的scope插槽，.row是该行的数据
    getPodDetail(e) {
      this.getpodmentDetailData.params.podment = e.row.metadata.name
      // 由于我写的后端传参名字是podment
      // this.PodDetailData.params.podment_name = e.row.metadata.name
      this.getpodmentDetailData.params.namespace = this.namespaceValue
      httpClient.get(this.getpodmentDetailData.url,{params: this.getpodmentDetailData.params})
      .then(res => {
        this.podmentDetail = res.data
        this.contentYaml = this.transYaml(this.podmentDetail)
        this.yamlDialog = true
      })
      .catch(res => {
        this.$message.error({
          message: res.msg
        })
      })
    },
    //更新
    updatePod(){
      let content = JSON.stringify(this.transObj(this.contentYaml))
      this.updatePodData.params.content = content
      this.updatePodData.params.namespace = this.namespaceValue
      // post请求不能使用{params: this.updatePodData.params} 这种形式
      httpClient.post(this.updatePodData.url, this.updatePodData.params )
      .then(res => {
        this.$message.success({
          message: res.msg
        })
        // 刷新列表
        this.getPods()
      })
      .catch(res => {
        this.$message.error({
          message: res.msg
        })
      })
      this.yamlDialog =  false
    },
  
    // 更新，删除
    //弹出确认框，用于危险操作的double check
    //obj是行数据（scope相当于一行的数据， scope.row相当于当前行的数据对象），opeateName是操作名，fn是操作的方法
    handleConfirm(obj,operateName,fn) {
    // handleConfirm( operateName) {
        this.confirmContent = '确认继续 ' + operateName + ' 操作吗？'
        //$confirm用于弹出确认框
        this.$confirm(this.confirmContent,'提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        })
        .then(() => {
          // 需要传入obj，否则下面无法拿到数据
          fn(obj)
          // 如果没有传入fn，可以使用下面这种方法
          // this.restartPod(obj)
        })
        .catch(() => {
            this.$message.info({
                message: '已取消操作'
            })          
        })
    },
    //删除方法
    delPod(obj){
      this.delPodData.params.podment = obj.row.metadata.name
      this.delPodData.params.namespace = this.namespaceValue
      httpClient.delete(this.delPodData.url, {params: this.delPodData.params})
      .then(res => {
          this.$message.success({
          message: res.msg
          })
      })
      .catch(res => {
          this.$message.error({
          message: res.msg
          })
      })
      // //关闭弹出框
      // this.delDialog = false
      //更新后重新获取列表
  
      this.getPods()
    }
    

  },
  watch: {
    namespaceValue: {
      handler(){
        localStorage.setItem('namespace',this.namespaceValue)
        this.currentPage = 1
        this.getPods()
      }
    }
  },
  beforeMount(){
    if(localStorage.getItem('namespace') !== undefined && localStorage.getItem('namespace') !== null){
      this.namespaceValue = localStorage.getItem('namespace')
    }
    this.getNamespacesList()
    this.getPods()
  }
}

</script>

<style scoped>
  .pod-head-card, .pod-body-card {
    border-radius: 1px;
    margin-bottom: 5px;
  }
  .pod-head-search {
    width: 160px;
    margin-right: 10px;
  }
  /* 数据表格podment名颜色 */
  .pod-body-podname {
    color: #4795EE;
  }
  /* pod名鼠标悬停 */
  .pod-body-podname:hover {
    color: rgb(84, 138,238);
    cursor: pointer;
    font-weight: bold;
  }

</style>